﻿using System;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using Microsoft.Reporting.WebForms;
using mojoPortal.Web.RS.SBM.AppCode.Lib;

 
namespace mojoPortal.Web.RS.SBM
{
    public partial class RSInvoiceReport : RSBasePage
    {
        int _companyid = 0;
        int _invoiceid = 0;
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                InitializeReadyServicePage("Invoice Report");
                RSUserIdentity userIdentity = GetRSUserIdentity(); //new RSUserIdentity();
                _companyid = userIdentity.RSCompanyId;

                if (Request.QueryString["invoiceid"] != null)
                    _invoiceid = Convert.ToInt32(Request.QueryString["invoiceid"].ToString());

                if (_companyid > 0 && _invoiceid > 0)
                {
                    LoadInvoiceDDL(_companyid);
                    SetReport(_companyid, _invoiceid);
                    int locationid = RSSBMCommonFunctions.GetLocationIDByInvoiceID(_companyid, _invoiceid);
                    ucLocationHeaderControl.LoadLocationHeader(_companyid, locationid);
                }

                //if (_invoiceid > 0)
                //    btnRunAdHocReport.Attributes.Add("OnClick", "java script:return fnLaunchWin('/RS/SBM/PreviewAdHocInvoice.aspx?invoiceid=" + _invoiceid.ToString() + "','AdHoc Invoice',600,600);");

            }
        }
        protected void btnRunAdHocReport_Click(object sender, EventArgs e)
        {
            if (Request.QueryString["invoiceid"] != null)
            {
                _invoiceid = Convert.ToInt32(Request.QueryString["invoiceid"].ToString());
                ucModalIFrameControl.ShowModal("/RS/SBM/PreviewAdHocInvoice.aspx?invoiceid=" + _invoiceid.ToString(), "600", "500");
            }
        }
        protected void ddlInvoiceId_SelectedIndexChanged(object sender, EventArgs e)
        {
            _invoiceid = Convert.ToInt32(ddlInvoiceId.SelectedValue);
            if (_invoiceid > 0)
                Response.Redirect("RSInvoiceReport.aspx?invoiceid=" + _invoiceid);
        }
        protected void btnReturn_Click(object sender, EventArgs e)
        {
            Response.Redirect(Session["PreviousURL"].ToString());
        }
        //protected void btnRunReport_Click(object sender, EventArgs e)
        //{
        //    RSUserIdentity userIdentity = GetRSUserIdentity(); //new RSUserIdentity();
        //    _companyid = userIdentity.RSCompanyId;
        //    _invoiceid = Convert.ToInt32(ddlInvoiceId.SelectedValue);
        //    if(_companyid > 0 && _invoiceid > 0)
        //        SetReport(_companyid, _invoiceid);
        //}
        private void LoadInvoiceDDL(int companyid)
        {
            SqlCommand myCommand;
            SqlDataReader myDataReader;
            String sqlSELECT = "SELECT InvoiceId FROM [rs_tblInvoice] WHERE CompanyID=@companyid ORDER BY InvoiceId ASC";
            SqlParameter param = new SqlParameter();
            SqlConnection myConnection;

            myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
            myCommand = new SqlCommand(sqlSELECT, myConnection);
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@companyid";
            param.Value = companyid;
            myCommand.Parameters.Add(param);
            myConnection.Open();
            myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
            ddlInvoiceId.Items.Clear();
            ddlInvoiceId.DataSource = myDataReader;
            ddlInvoiceId.DataTextField = "InvoiceId";
            ddlInvoiceId.DataValueField = "InvoiceId";
            ddlInvoiceId.DataBind();
            ddlInvoiceId.Items.Insert(0, new ListItem("< Please select >", "0"));
            myConnection.Close();
        }
        protected void ObjectDataSource_OnObjectCreated(object sender, ObjectDataSourceEventArgs e)
        {
            if (e.ObjectInstance != null)
            {
                SqlConnection conn = new SqlConnection();
                conn.ConnectionString = ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString();
                e.ObjectInstance.GetType().GetProperty("Connection").SetValue(e.ObjectInstance, conn, null);
            }
        }

        private void SetReport(int companyid, int invoiceid)
        {
            ddlInvoiceId.SelectedValue = invoiceid.ToString();
            int WorkOrderid = RSSBMCommonFunctions.GetWorkOrderIDByInvoiceID(companyid, invoiceid);
            vwWorkOrderInvoiceDataObjectDataSource.SelectParameters["workorderid"].DefaultValue = WorkOrderid.ToString();
            vwWorkOrderInvoiceDataObjectDataSource.SelectParameters["invoiceid"].DefaultValue = invoiceid.ToString();
            vwWorkOrderInvoiceDataObjectDataSource.SelectParameters["companyid"].DefaultValue = companyid.ToString();

            vwWorkOrderInvoiceItemDataObjectDataSource.SelectParameters["workorderid"].DefaultValue = WorkOrderid.ToString();
            vwWorkOrderInvoiceItemDataObjectDataSource.SelectParameters["companyid"].DefaultValue = companyid.ToString();

            tblCompanyObjectDataSource.SelectParameters["companyid"].DefaultValue = companyid.ToString();

            LocalReport rep = ReportViewer1.LocalReport;
            rep.ReportPath = "RS\\AppData\\SBM\\Reports\\RDLC\\RSInvoiceReport.rdlc";
            rep.DataSources.Clear();

            ReportDataSource dsWorkOrderInvoice = new ReportDataSource("vwWorkOrderInvoice", vwWorkOrderInvoiceDataObjectDataSource);
            ReportDataSource dsWorkOrderInvoiceItem = new ReportDataSource("vwWorkOrderInvoiceItem", vwWorkOrderInvoiceItemDataObjectDataSource);
            ReportDataSource dsCompany = new ReportDataSource("tblCompany", tblCompanyObjectDataSource);

            rep.DataSources.Add(dsWorkOrderInvoice);
            rep.DataSources.Add(dsWorkOrderInvoiceItem);
            rep.DataSources.Add(dsCompany);

            rep.Refresh();

            string rp = "";
            if (IsPaidInFull(companyid, invoiceid))
            {
                rp = "1";
            }
            ReportParameter reportParam = new ReportParameter("isPaid", rp);
            ReportViewer1.LocalReport.SetParameters(reportParam);
        }

        public bool IsPaidInFull(int companyid, int invoiceid)
        {
            bool isPaid = false;
            if (companyid > 0 && invoiceid > 0)
            {
                String strSQL = "SELECT i.InvoiceId,i.BalanceDue_CF FROM rs_tblInvoice i WHERE i.InvoiceId=@InvoiceId AND i.CompanyId=@CompanyId";
                SqlCommand myCommand;
                SqlParameter param;
                SqlConnection myConnection;
                myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
                myCommand = new SqlCommand(strSQL, myConnection);
                SqlDataReader myDataReader;

                param = new SqlParameter();
                param.SqlDbType = SqlDbType.Int;
                param.ParameterName = "@Invoiceid";
                param.Value = invoiceid;
                myCommand.Parameters.Add(param);

                param = new SqlParameter();
                param.SqlDbType = SqlDbType.Int;
                param.ParameterName = "@Companyid";
                param.Value = companyid;
                myCommand.Parameters.Add(param);

                myConnection.Open();
                myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
                if (myDataReader.HasRows)
                {
                    myDataReader.Read();
                    if(myDataReader["BalanceDue_CF"] != DBNull.Value)
                    {
                        double balanceDue = Convert.ToDouble(myDataReader["BalanceDue_CF"].ToString());
                        if (balanceDue <= 0)
                            isPaid = true;
                    }
                }
                myConnection.Close();
            }
            return isPaid;
        }
    }
}